<?php
/**
 * PatientSignalController class file.
 *
 * @package   controllers
 * @since     1.0
 * @filesource
 */

/**
 * The controller for patient signal related actions and pages.
 * Controller class is also responsible for rendering page.
 * @author Patrick
 *
 */
class PatientSignalController extends Controller
{
	/**
	 * By default the actions in patient signal pages will use 1 column layout.
	 * @var string
	 */
	public $layout='//layouts/column1';

	/**
	 * Return a list of filters that will be used to control access.
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter which is declared in $this->filters().
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow', // allow authenticated user to perform specified actions
		// The actions will be checked further depends on configuration and assignment.
				'actions'=>array('index','view','update','upload','uploadFilesPlupload','uploadFilesInfo','admin','delete','downloadFile','downloadResult','cancelUpload','updateFiles','updateFilesSave','deleteSignalFile'),
				'users'=>array('@'),
		),
		array('deny',  // deny all users
				'users'=>array('*'),
		),
		);
	}

	/** 
	 * Specifies the action classes that will be integrated into this class.
	 * These action classes will be called by defined name as a normal action method of this class.
	 * @return array a list of action classes that will be integrated in this class.
	 * @see CController::actions()
	 * @see directory ./patientSignal for the action classes.
	 */
	public function actions(){
		return array(
			'upload'=>array(
				'class'=>'application.controllers.patientSignal.UploadAction'
				),
			'uploadFilesInfo'=>array(
				'class'=>'application.controllers.patientSignal.UploadFilesInfoAction'
				),
			'uploadFilesPlupload'=>array(
				'class'=>'application.controllers.patientSignal.UploadFilesPluploadAction'
				),
			'cancelUpload'=>array(
				'class'=>'application.controllers.patientSignal.CancelUploadAction'
				),
			'updateFiles'=>array(
				'class'=>'application.controllers.patientSignal.UpdateFilesAction'
				),
			'updateFilesSave'=>array(
				'class'=>'application.controllers.patientSignal.UpdateFilesSaveAction'
				),
			);
	}

	/**
	 * Displays a particular patient signal information.
	 * @param integer $id the ID of the patient signal to be displayed
	 * @throws CHttpException if current has no view access to the patient signal.
	 */
	public function actionView($id)
	{
		$model=$this->loadModel($id);
		if(!Yii::app()->user->checkAccess('signalView',array(
		'organizationId'=>$model->organizationId
		))){
			throw new CHttpException(403,'You do not have permission to view this record.');
		}
		$this->render('view',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular patient signal's basic information.
	 * This action will display a form for updating basic information of a patient signal if no data posted back.
	 * If data posted back, it will validate the data and try to save it to database.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the patient signal to be updated
	 * @throws CHttpException if current has no update access to the patient signal.
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		//check if the user has right to download a file.
		if(!Yii::app()->user->checkAccess('signalUpdate',array('organizationId'=>$model->organizationId))){
			throw new CHttpException(403,'You do not have permission to update this record.');
		}

		if(isset($_POST['PatientSignal']))
		{
			$model->attributes=$_POST['PatientSignal'];

			if($model->save())
			$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular patient signal, all related uploaded patient signal files and result files.
	 * If deletion is successful, the browser will be redirected to the 'index' page.
	 * @param integer $id the ID of the patient signal to be deleted
	 * @throws CHttpException if current user has no delete right to the patient signal.
	 * @throws CHttpException if the delete request is not POST request.
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model=$this->loadModel($id);

			//check if the user has right to download a file.
			if(!Yii::app()->user->checkAccess('signalDelete',array('organizationId'=>$model->organizationId))){
				throw new CHttpException(403,'You do not have permission to delete this record.');
			}

			$model->delete();

			$this->redirect(array('index'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all patient signals under two tab - My uploads and By Organizations.
	 * This action method also processes request to download result files of patient signals
	 * that are the result by searching under tab - By Organizations.
	 */
	public function actionIndex()
	{
		// if it is result download request, process the request, if there is a zip file to export,
		// prevent to do following processing.
		if(isset($_GET['download']) && $this->downloadResults())
			return;

		$this->layout='//layouts/column1';
		
		// Get patient signals uploaded by current user.
		$myUploadedDataProvider=new CActiveDataProvider('PatientSignal',array(
			'pagination'=>array('pageSize'=>10),
			'criteria'=>array(
				'condition'=>'userId=:userId',
				'params'=>array(':userId'=>Yii::app()->user->id),
				'order' => 'createDate DESC',
				'with'=>array('organization','disorder')
		)
		));
		// Get patient signals got by search condition.
		$model=new PatientSignalSearch();
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PatientSignalSearch'])){
			$model->attributes=$_GET['PatientSignalSearch'];
		}

		$this->render('index',array(
			'myUploadedDataProvider'=>$myUploadedDataProvider,
			'byOrganizationModel'=>$model,
		));
	}

	/**
	 * Returns the PatientSignal object based on the primary key given in the GET variable.
	 * @param integer the ID of the patient signal to be loaded
	 * @return PatientSignal
	 * @throws CHttpException If the PatientSignal object is not found
	 */
	public function loadModel($id)
	{
		$model=PatientSignal::model()->findByPk((int)$id);
		if($model===null)
		throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation. The results will be displayed on the page.
	 * @param PatientSignal the PatientSignal object to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='patient-signal-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	/**
	 * Action to download a file for the specified $fileId in a specified signal record.
	 * @param int $fileId ID parameter from the GET http request. Used to look up file by this id.
	 * @throws CHttpException if access is denied or action is illegal
	 * @throws CHttpException if the request file does not exists.
	 */
	public function actionDownloadFile($fileId){
		$signalFile=PatientSignalFile::model()->findByPk($fileId);
		if($signalFile===null)
			throw new CHttpException(404,'The requested file does not exist.');
		//check if the user has right to download a file.
		if(!Yii::app()->user->checkAccess('signalDownload',array('organizationId'=>$signalFile->patientSignal->organizationId))){
			throw new CHttpException(403,'You do not have permission to download this record.');
		}
		$filePath=$signalFile->patientSignal->signalPath.DIRECTORY_SEPARATOR.$signalFile->filename;
		// check if the requested file exists.
		if (!file_exists($filePath)) {
			throw new CHttpException(403,'The requested file '
			.$signalFile->filename
			.' for signal subject "'.
			$signalFile->patientSignal->subject
			.'" does not exist, please contact administrator to solve this issue.');
		}
		// stream the file and allow user download it.
		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename='.$signalFile->filename);
		readfile($filePath);
		Yii::app()->end();
	}

	/**
	 * Action to download result file in a specified signal record.
	 * @param int $id ID parameter from the GET http request. Used to look up signal by this id.
	 * @throws CHttpException if access is denied or action is illegal
	 * @throws CHttpException if the request file does not exists.
	 */
	public function actionDownloadResult($id){
		$model=$this->loadModel($id);

		//check if the user has right to download a file.
		if(!Yii::app()->user->checkAccess('signalDownload',array('organizationId'=>$model->organizationId))){
			throw new CHttpException(403,'You do not have permission to download this record.');
		}
		// check if the file name of requested file type is empty.
		if (empty($model->resultFileName)) {
			throw new CHttpException(403,'Invalid Request, please not do it again.');
		}
		$filePath=$model->signalPath.DIRECTORY_SEPARATOR.$model->resultFileName;
		// check if the requested file exists.
		if (!file_exists($filePath)) {
			throw new CHttpException(403,'The requested file does not exist, please contact administrator to solve this issue.');
		}
		// stream the file and allow user download it.
		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename='.$model->resultFileName);
		readfile($filePath);
		Yii::app()->end();
	}

	/**
	 * Action to delete an uploaded file in a signal record.
	 * If successful, the browser will be redirected to update files page.
	 * @param int $id id of file to be deleted.
	 * @throws CHttpException if the file to be deleted does not exists.
	 * @throws CHttpException if access is denied.
	 * @throws CHttpException if the patient signal is not editable.
	 */
	public function actionDeleteSignalFile($fileId) {
		$signalFile=PatientSignalFile::model()->findByPk($fileId);
		if($signalFile===null)
			throw new CHttpException(404,'The requested file does not exist.');

		//check if the user has right to download a file.
		if(!Yii::app()->user->checkAccess('signalUpdate',array('organizationId'=>$signalFile->patientSignal->organizationId))){
			throw new CHttpException(403,'You do not have permission to update this record.');
		}
		if(!$signalFile->patientSignal->isEditable()){
			throw new CHttpException(403,'This signal cannot be updated.');
		
		}
		
		//check at least one file should present
		if($signalFile->patientSignal->signalFilesCount>1){
			$signalFile->delete();
		}
		$this->redirect(array('updateFiles','id'=>$signalFile->patientSignalId));
	}
	
	/**
	 * Download a zip file which includes all result files of patient signals that are the result of search on index page.
	 * If there is no patient signals found by the conditions or the result patient signal has no result files, no file will be exported.
	 * @return true | false - has zip file to export | has no zip file.
	 * @throws CHttpException if can not create the result zip file
	 * @throws CHttpException if recorded result file does not exists.
	 */
	private function downloadResults(){
		$model=new PatientSignalSearch();
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PatientSignalSearch'])){
			$model->attributes=$_GET['PatientSignalSearch'];
		}
		$signals=PatientSignal::model()->findAll($model->createCriteria());
		// if no signals are found by the condition, no result return.
		if (count($signals)==0)
			return false;
		
		$tempfile=sys_get_temp_dir().DIRECTORY_SEPARATOR.uniqid('download').'.zip';
		$zip = new ZipArchive();
		//create the file and throw the error if unsuccessful
		if ($zip->open($tempfile, ZIPARCHIVE::CREATE )!==TRUE) {
			throw new CHttpException(500, "Cannot open output stream");
		}
		$fileCount=0;
		//add each files of $file_name array to archive
		foreach ($signals as $signal) {
			if($signal->status==PatientSignal::STATUS_PROCESSED){
				$filePath=$signal->signalPath.DIRECTORY_SEPARATOR.$signal->resultFileName;
				// check if the requested file exists.
				if (!file_exists($filePath)) {
					throw new CHttpException(403,'The requested file for signal #'.$signal->id.' does not exist, please contact administrator to solve this issue.');
				}
				$zip->addFile($filePath,$signal->resultFileName);
				$fileCount++;
			}
		}
		$zip->close();
		if($fileCount>0){
			header("Content-type: application/zip");
			header("Content-Disposition: attachment; filename=signal-result-[".$fileCount."]-".date('Y-m-d').'.zip');
			header("Pragma: no-cache");
			header("Expires: 0");
			readfile("$tempfile");
			return true;
		}
		return false;
	}
}